using DocumentCreationSystem.Services;
using DocumentCreationSystem.Views.Dialogs;
using Microsoft.Extensions.DependencyInjection;
using System.Windows;
using System.Windows.Controls;

namespace DocumentCreationSystem.Views.Controls;

/// <summary>
/// AI工具面板
/// </summary>
public partial class AIToolsPanel : UserControl
{
    private readonly IAIToolsService _aiToolsService;
    private string _searchQuery = string.Empty;

    public AIToolsPanel()
    {
        InitializeComponent();
        
        // 从依赖注入容器获取服务
        _aiToolsService = App.ServiceProvider?.GetService<IAIToolsService>() 
            ?? throw new InvalidOperationException("无法获取AI工具服务");

        LoadTools();
    }

    /// <summary>
    /// 搜索查询属性
    /// </summary>
    public string SearchQuery
    {
        get => _searchQuery;
        set
        {
            _searchQuery = value;
            FilterTools();
        }
    }

    /// <summary>
    /// 加载工具列表
    /// </summary>
    private async void LoadTools()
    {
        try
        {
            StatusText.Text = "正在加载工具...";
            
            var tools = await _aiToolsService.GetAvailableToolsAsync();
            
            StatusText.Text = $"已加载 {tools.Count} 个工具";
        }
        catch (Exception ex)
        {
            StatusText.Text = $"加载工具失败: {ex.Message}";
            MessageBox.Show($"加载AI工具失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }

    /// <summary>
    /// 过滤工具
    /// </summary>
    private async void FilterTools()
    {
        try
        {
            if (string.IsNullOrWhiteSpace(_searchQuery))
            {
                // 显示所有工具
                ShowAllTools();
                return;
            }

            var filteredTools = await _aiToolsService.SearchToolsAsync(_searchQuery);
            
            // 隐藏所有工具按钮
            HideAllTools();
            
            // 显示匹配的工具
            foreach (var tool in filteredTools)
            {
                ShowToolButton(tool.Id);
            }

            StatusText.Text = $"找到 {filteredTools.Count} 个匹配的工具";
        }
        catch (Exception ex)
        {
            StatusText.Text = $"搜索失败: {ex.Message}";
        }
    }

    /// <summary>
    /// 显示所有工具
    /// </summary>
    private void ShowAllTools()
    {
        foreach (UIElement element in ToolsContainer.Children)
        {
            element.Visibility = Visibility.Visible;
        }
    }

    /// <summary>
    /// 隐藏所有工具
    /// </summary>
    private void HideAllTools()
    {
        foreach (UIElement element in ToolsContainer.Children)
        {
            if (element is Button)
            {
                element.Visibility = Visibility.Collapsed;
            }
        }
    }

    /// <summary>
    /// 显示指定工具按钮
    /// </summary>
    private void ShowToolButton(string toolId)
    {
        foreach (UIElement element in ToolsContainer.Children)
        {
            if (element is Button button && button.Tag?.ToString() == toolId)
            {
                button.Visibility = Visibility.Visible;
                break;
            }
        }
    }

    /// <summary>
    /// 搜索按钮点击事件
    /// </summary>
    private void SearchButton_Click(object sender, RoutedEventArgs e)
    {
        SearchQuery = SearchTextBox.Text;
    }

    /// <summary>
    /// 工具按钮点击事件
    /// </summary>
    private async void ToolButton_Click(object sender, RoutedEventArgs e)
    {
        if (sender is not Button button || button.Tag is not string toolId)
            return;

        try
        {
            StatusText.Text = $"正在准备工具: {toolId}";

            // 获取工具参数
            var parameters = await _aiToolsService.GetToolParametersAsync(toolId);
            
            // 如果工具需要参数，显示参数输入对话框
            Dictionary<string, object> toolParameters = new();
            
            if (parameters.Any())
            {
                var parameterDialog = new AIToolParameterDialog(toolId, parameters);
                if (parameterDialog.ShowDialog() != true)
                {
                    StatusText.Text = "已取消";
                    return;
                }
                
                toolParameters = parameterDialog.GetParameters();
            }

            // 验证参数
            var validation = await _aiToolsService.ValidateParametersAsync(toolId, toolParameters);
            if (!validation.IsValid)
            {
                var errorMessage = string.Join("\n", validation.Errors);
                MessageBox.Show($"参数验证失败:\n{errorMessage}", "参数错误", MessageBoxButton.OK, MessageBoxImage.Warning);
                StatusText.Text = "参数验证失败";
                return;
            }

            StatusText.Text = $"正在执行工具: {toolId}";

            // 执行工具
            var result = await _aiToolsService.ExecuteToolAsync(toolId, toolParameters);

            // 显示结果
            var resultDialog = new AIToolResultDialog(result);
            resultDialog.ShowDialog();

            StatusText.Text = result.IsSuccess ? 
                $"工具执行成功 ({result.ExecutionTimeMs}ms)" : 
                $"工具执行失败: {result.ErrorDetails}";
        }
        catch (Exception ex)
        {
            StatusText.Text = $"执行失败: {ex.Message}";
            MessageBox.Show($"执行工具失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }

    /// <summary>
    /// 刷新工具列表
    /// </summary>
    public async void RefreshTools()
    {
        LoadTools();
    }

    /// <summary>
    /// 获取工具统计信息
    /// </summary>
    public async Task<string> GetToolStatisticsAsync()
    {
        try
        {
            var statistics = await _aiToolsService.GetToolStatisticsAsync();
            
            return $"总工具数: {statistics.TotalTools}\n" +
                   $"启用工具: {statistics.EnabledTools}\n" +
                   $"总使用次数: {statistics.TotalUsageCount}\n" +
                   $"平均成功率: {statistics.AverageSuccessRate:F1}%\n" +
                   $"最常用工具: {string.Join(", ", statistics.MostUsedTools.Take(3))}";
        }
        catch (Exception ex)
        {
            return $"获取统计信息失败: {ex.Message}";
        }
    }

    /// <summary>
    /// 执行指定工具
    /// </summary>
    /// <param name="toolId">工具ID</param>
    /// <param name="parameters">工具参数</param>
    /// <returns>执行结果</returns>
    public async Task<bool> ExecuteToolAsync(string toolId, Dictionary<string, object> parameters)
    {
        try
        {
            StatusText.Text = $"正在执行工具: {toolId}";

            var result = await _aiToolsService.ExecuteToolAsync(toolId, parameters);

            StatusText.Text = result.IsSuccess ? 
                $"工具执行成功 ({result.ExecutionTimeMs}ms)" : 
                $"工具执行失败: {result.ErrorDetails}";

            return result.IsSuccess;
        }
        catch (Exception ex)
        {
            StatusText.Text = $"执行失败: {ex.Message}";
            return false;
        }
    }

    /// <summary>
    /// 获取工具使用历史
    /// </summary>
    /// <param name="toolId">工具ID</param>
    /// <param name="limit">限制数量</param>
    /// <returns>使用历史</returns>
    public async Task<List<string>> GetToolHistoryAsync(string toolId, int limit = 5)
    {
        try
        {
            var history = await _aiToolsService.GetToolUsageHistoryAsync(toolId, limit);
            
            return history.Select(h => 
                $"{h.UsedAt:yyyy-MM-dd HH:mm:ss} - " +
                $"{(h.IsSuccess ? "成功" : "失败")} - " +
                $"{h.ExecutionTimeMs}ms" +
                (string.IsNullOrEmpty(h.ErrorMessage) ? "" : $" - {h.ErrorMessage}")
            ).ToList();
        }
        catch (Exception ex)
        {
            return new List<string> { $"获取历史失败: {ex.Message}" };
        }
    }
}
